package jsyf.oa.dao.wechat.service_company;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.device.TagAliasResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import jsyf.com.dao.BaseJdbcDao;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.wechat.service_otherCompany.CompanyMessageDao;
import jsyf.oa.entity.wechat.service_company.TokenEntity;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_company.CompanyTokenFacade;
import jsyf.oa.idao.BaseDao;
import jsyf.oa.ientity.IBaseEntity;
import jsyf.oa.service.wechat.service_company.HttpUtil;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.SIGN_REMIND;

@Repository
public class TokenDao extends BaseDao {

    //private static final Logger LOG = Logger.getLogger(TokenDao.class);

    @Autowired
    private CompanyTokenFacade companyTokenFacade;

    @Autowired
    private CompanyMessageDao companyMessageDao;

    @Value("${wechat.agentId}")
    private String agentId;

    @Value("${wechat.secret}")
    private String cropSecret;

    public class PushTemplate {

        public static final String MONEY_AUDIT_NOTIFY = "%1s的用款申请需要您审核";

        public static final String EVENT_AUDIT_NOTIFY = "%1s的临时事项申请需要您审核";

        public static final String BUSINESS_AUDIT_NOTIFY = "%1s的商务条件申请需要您审核";

        public static final String COST_AUDIT_NOTIFY = "%1s的临时费用申请需要您审核";

        public static final String COST_APPLY_NOTIFY = "%1s，你好!,您的临时费用申请需要您补充";

        public static final String CONTRACT_AUDIT_NOTIFY = "%1s的合同申请需要您审核";
    }

    public class MsgTemplate {

        //行政采购申购消息提醒
        //---审核通知---
        public static final String PSI_AUDIT_AUDIT = "%1s，你好!\n有一个行政采购申请需要你审核。\n申请人：%2s\n申请时间：%3s";
        //---审核通过---
        public static final String PSI_AUDIT_PASS = "%1s，你好!\n你提交的行政采购申请已通过!\n审核人：%2s\n审核时间：%3s";
        //---审核驳回---
        public static final String PSI_AUDIT_REJECT = "%1s，你好!\n你提交的行政采购申请已被驳回!\n原因：%2s。\n审核人：%3s\n审核时间：%4s";
        //消息框提示审核人
        public static final String PSI_AUDIT_ONE = "【审核】\n%1s提交了行政采购申请，请审核！";
        //审核通过提示申请人
        public static final String PSI_AUDIT_TWO = "【通知】您提交的行政采购申请\n%1s\n已通过！";
        //审核驳回提示申请人
        public static final String PSI_AUDIT_THREE = "【通知】您提交的行政采购申请\n%1s\n已驳回！";

        //---审核通知---
        public static final String REPO_AUDIT_AUDIT = "%1s，你好!\n有一个行政物品出库申请需要你审核。\n申请人：%2s\n申请时间：%3s";
        //---审核通过---
        public static final String REPO_AUDIT_PASS = "%1s，你好!\n你提交的行政物品出库申请已通过!\n审核人：%2s\n审核时间：%3s";
        //---审核驳回---
        public static final String REPO_AUDIT_REJECT = "%1s，你好!\n你提交的行政物品出库申请已被驳回!\n原因：%2s。\n审核人：%3s\n审核时间：%4s";
        //消息框提示审核人
        public static final String REPO_AUDIT_ONE = "【审核】\n%1s提交了行政物品出库申请，请审核！";
        //审核通过提示申请人
        public static final String REPO_AUDIT_TWO = "【通知】您提交的行政物品出库申请\n%1s\n已通过！";
        //审核驳回提示申请人
        public static final String REPO_AUDIT_THREE = "【通知】您提交的行政物品出库申请\n%1s\n已驳回！";

        //周三商机跟踪消息提醒
        //---审核通知---
        public static final String TRUCK_AUDIT_AUDIT = "%1s，你好!\n有一个每周三商机跟踪申请需要你审核。\n申请人：%2s\n申请时间：%3s";
        //---审核通过---
        public static final String TRUCK_AUDIT_PASS = "%1s，你好!\n你提交的每周三商机跟踪申请已通过!\n审核人：%2s\n审核时间：%3s";
        //---审核驳回---
        public static final String TRUCK_AUDIT_REJECT = "%1s，你好!\n你提交的每周三商机跟踪申请已被驳回!\n原因：%2s。\n审核人：%3s\n审核时间：%4s";
        //消息框提示审核人
        public static final String TRUCK_AUDIT_ONE = "【审核】\n%1s提交了每周三商机跟踪申请，请审核！";
        //审核通过提示申请人
        public static final String TRUCK_AUDIT_TWO = "【通知】您提交的客户为\"%1s\"的每周三商机跟踪申请\n%2s\n已通过！";
        //审核驳回提示申请人
        public static final String TRUCK_AUDIT_THREE = "【通知】您提交的客户为\"%1s\"的每周三商机跟踪申请\n%2s\n已驳回！";

        //------用款申请------

        /**
         * 用款申请消息框提示--审核
         */
        public static final String MONEY_AUDIT_ONE = "【审核】\n%1s提交了\"%2s\"用款申请，请审核！";
        /**
         * 用款申请消息框提示--审核通过提示申请人
         */
        public static final String MONEY_AUDIT_TWO = "【通知】您提交的\"%1s\"用款申请\n%2s\n已通过！";
        /**
         * 用款申请消息框提示--审核驳回提示申请人
         */
        public static final String MONEY_AUDIT_THREE = "【通知】您提交的\"%1s\"用款申请\n%2s\n已驳回！";
        /**
         * 用款申请消息框提示--审核人审核通过提示
         */
        public static final String MONEY_AUDIT_FOUR = "【通知】\n%1s提交的\"%2s\"用款申请您已通过！";
        /**
         * 用款申请消息框提示--审核人审核驳回提示
         */
        public static final String MONEY_AUDIT_FIVE = "【通知】\n%1s提交的\"%2s\"用款申请您已驳回！";
        /**
         * 用款申请消息框提示--付款成功提示
         */
        public static final String MONEY_PAY_ONE = "【通知】您提交的\"%1s\"用款申请\n%2s\n已付款！";
        /**
         * 临时事项消息框提示-审核
         */
        public static final String EVENT_AUDIT_ONE = "【审核】\n%1s提交了\"%2s\"临时事项，请审核！";
        /**
         * 临时事项消息框提示--申请人审核通过提示
         */
        public static final String EVENT_AUDIT_TWO = "【通知】您提交的\"%1s\"临时事项\n已通过！\n审核人：%2s";
        /**
         * 临时事项消息框提示--审核人审核通过提示
         */
        public static final String EVENT_AUDIT_FOUR = "【通知】\"%1s\"提交的\"%2s\"临时事项\n已通过！\n";
        /**
         * 临时事项消息框提示--审核驳回提示
         */
        public static final String EVENT_AUDIT_THREE = "【通知】您提交的\"%1s\"临时事项\n已驳回！";
        /**
         * 审核通过
         */
        public static final String MONEY_AUDIT_PASS = "%1s，你好!\n你提交的\"%2s\"，金额¥%3s元\n，申请已通过!\n审核人：%4s\n审核时间：%5s";
        /**
         * 审核驳回
         */
        public static final String MONEY_AUDIT_REJECT = "%1s，你好!\n你提交的\"%2s\"，金额¥%3s元\n，申请已被驳回!\n原因：%4s\n审核人：%5s\n审核时间：%6s";
        /**
         * 微信审核通过
         */
        public static final String MONEY_AUDIT_PASSONE = "%1s，你好!\n\"%2s\"已审核，金额¥%3s元。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/money/detail_new.html?id=%6s&currentAuditorId=%7s\">已通过</a>";
        /**
         * 微信审核驳回
         */
        public static final String MONEY_AUDIT_REJECTONE = "%1s，你好!\n\"%2s\"已审核，金额¥%3s元。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/money/detail_new.html?id=%6s&currentAuditorId=%7s\">已驳回</a>";
        /**
         * 微信审核中
         */
        public static final String MONEY_AUDIT_AUDIT = "%1s，你好!\n有一笔\"%2s\"需要审核，金额¥%3s元。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/money/detail_new.html?id=%6s&currentAuditorId=%7s&receiverId=%8s\">点此审核</a>";
        public static final String MONEY_AUDIT_AUDIT_PC = "%1s，你好!\n有一笔\"%2s\"需要审核，金额¥%3s元。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/money/detail_new.html?id=%6s&currentAuditorId=%7s\">点此审核</a>";
        /**
         * 付款审核中
         */
        public static final String MONEY_PAY_AUDIT = "%1s，你好!\n有一笔\"%2s\"需要付款审核，金额¥%3s元。\n申请人：%4s\n申请时间：%5s";
        /**
         * 付款通过
         */
        public static final String MONEY_PAY_PASS = "%1s，你好!\n你提交的\"%2s\"，金额¥%3s元\n，已付款!\n付款人：%4s\n付款时间：%5s";
        /**
         * 付款驳回
         */
        public static final String MONEY_PAY_REJECT = "%1s，你好!\n你提交的\"%2s\"，金额¥%3s元\n，付款被驳回!\n原因：4%sn审核人：%5s\n审核时间：%6s";
        /**
         * 抄送人驳回
         */
        public static final String MONEY_COPIER_REJECT = "%1s，你好!\n你提交的\"%2s\"，用款申请已被驳回!\n原因：%3s。";

        //------费用申请------

//        public static final String COST_AUDIT_AUDIT = "%1s，你好!\n有一个临时费用申请\"%2s\"需要审核。\n说明：%3s。\n申请人：%4s\n申请时间：%5s" + "\n提示：微信不能审核，请到app审核";
        /**
         * 微信审核中
         */
        public static final String COST_AUDIT_AUDIT = "%1s，你好!\n有一个临时费用申请\"%2s\"需要审核。\n说明：%3s。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/cost/detail_new.html?id=%6s&currentAuditorId=%7s\">点此审核</a>";

        /**
         * 微信审核通过
         */
        public static final String COST_AUDIT_PASSONE = "%1s，你好!\n\"%2s\"已审核。\n说明：%3s。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/cost/detail_new.html?id=%6s&currentAuditorId=%7s\">已通过</a>";
        /**
         * 微信审核驳回
         */
        public static final String COST_AUDIT_REJECTONE = "%1s，你好!\n\"%2s\"已审核。\n说明：%3s。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/cost/detail_new.html?id=%6s&currentAuditorId=%7s\">已驳回</a>";

        /**
         * 审核驳回
         */
        public static final String COST_AUDIT_REJECT = "%1s，你好!\n你提交的临时费用申请\"%2s\"，申请已被驳回!\n 原因：%3s\n审核人：%4s\n审核时间：%5s";
        /**
         * 审核通过
         */
        public static final String COST_AUDIT_PASS = "%1s，你好!\n你提交的临时费用申请\"%2s\"，申请已通过!\n审核人：%3s\n审核时间：%4s";

        public static final String COST_COPIER_REJECT = "%1s，你好!\n你提交的临时费用申请\"%2s\"，申请已被驳回!\n原因：%3s。";

        public static final String COST_AUDIT_CANCEL = "%1s，你好!\n有一个临时费用申请\"%2s\"已取消。\n说明：%3s。\n申请人：%4s\n申请时间：%5s" + "\n提示：微信不能审核，请到app审核";
        //------临时事项------
        public static final String SIGN_REMIND = "早上好！ 开始今天的签到吧！\n %1s";
        public static final String TEXT = "您好！ 这是一条测试消息！\n %1s";
        /**
         * 审核中
         */
//        public static final String EVENT_AUDIT_AUDIT = "%1s，你好!\n有一个临时事项\"%2s\"需要审核。\n主题：%3s。\n申请人：%4s\n申请时间：%5s";
        /**
         * 微信审核中
         */
        public static final String EVENT_AUDIT_AUDIT = "%1s，你好!\n有一个临时事项\"%2s\"需要审核。\n主题：%3s。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/tmpevent/detail_new.html?id=%6s&currentAuditorId=%7s\">点此审核</a>";

        /**
         * 微信审核通过
         */
        public static final String EVENT_AUDIT_PASSONE = "%1s，你好!\n\"%2s\"已审核。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/tmpevent/detail_new.html?id=%6s&currentAuditorId=%7s\">已通过</a>";
        /**
         * 微信审核驳回
         */
        public static final String EVENT_AUDIT_REJECTONE = "%1s，你好!\n\"%2s\"已审核。\n申请人：%4s\n申请时间：%5s\n\n" +
                "<a href=\"http://oa.yingfeng365.com/page/apply/tmpevent/detail_new.html?id=%6s&currentAuditorId=%7s\">已驳回</a>";

        /**
         * 审核通过
         */
        public static final String EVENT_AUDIT_PASS = "%1s，你好!\n你提交的临时事项\"%2s\"，申请已通过!\n审核人：%3s\n审核时间：%4s";
        /**
         * 审核驳回
         */
        public static final String EVENT_AUDIT_REJECT = "%1s，你好!\n你提交的临时事项\"%2s\"，申请已被驳回!\n主题：%3s。\n原因：%4s\n审核人：%5s\n审核时间：%6s";
        /**
         * 抄送人驳回
         */
        public static final String EVENT_COPIER_REJECT = "%1s，你好!\n你提交的临时事项\"%2s\"，申请已被驳回!\n主题：%3s。\n原因：%4s。";

        //------商务条件申请------

        /**
         * 审核中
         */
        public static final String BUSINESS_AUDIT_AUDIT = "%1s，你好!\n有一个商务条件申请需要审核。\n机型：%2s\n价格：¥%3s 万元\n申请人：%4s\n申请时间：%5s";
        /**
         * 信审中
         */
        public static final String BUSINESS_TRUST_AUDIT = "%1s，你好!\n有一个商务条件申请需要信审。\n机型：%2s\n价格：¥%3s 万元\n申请人：%4s\n申请时间：%5s";


        /**
         * 审核通过
         */
        public static final String BUSINESS_AUDIT_PASS = "%1s，你好!\n你提交的商务条件，申请已通过!\n机型：%2s\n价格：¥%3s 万元\n审核人：%4s\n审核时间：%5s";
        /**
         * 信审通过
         */
        public static final String BUSINESS_TRUST_PASS = "%1s，你好!\n你提交的商务条件，申请已通过!\n机型：%2s\n价格：¥%3s 万元\n审核人：%4s\n审核时间：%5s";

        /**
         * 审核驳回
         */
        public static final String BUSINESS_AUDIT_REJECT = "%1s，你好!\n你提交的商务条件申请，已被驳回!\n机型：%2s\n价格：¥%3s 万元\n原因：%4s。\n审核人：%5s\n审核时间：%6s";
        /**
         * 信审驳回
         */
        public static final String BUSINESS_TRUST_REJECT = "%1s，你好!\n你提交的商务条件申请，信审不通过已被驳回!\n机型：%2s\n价格：¥%3s 万元\n原因：%4s。\n审核人：%5s\n审核时间：%6s";

        /**
         * 抄送人驳回
         */
        public static final String BUSINESS_COPIER_REJECT = "%1s，你好!\n你提交的商务条件申请，已被驳回!\n机型：%2s\n价格：¥%3s 万元\n原因：%4s。";

        //------请假------
        /**
         * 请假通知
         */
        public static final String LEAVE_NOTICE = "你好：\n%1s，申请请假\n请假日期：%2s\n请假原因：%3s。";
        /**
         * 请假通知自己
         */
        public static final String LEAVE_NOTICE_SELF = "%1s，你好！\n请假申请已提交成功。\n请假日期：%2s\n请假原因：%3s。";

        //------提示------
        /**
         * 考勤提示
         */
        public static final String SIGNIN_NOTICE = "你好，%1s";

        //-------库存---------
        /**
         * 需要审核
         */
        public static final String Device_AUDIT_AUDIT = "%1s，你好!\n有一个新机入库申请需要审核。\n机型:%2s,\n序列号:%3s,\n申请人:%4s,\n申请时间:%5s";
        public static final String Device_STATE_AUDIT = "%1s，你好!\n有一个新机交付申请需要审核。\n机型:%2s,\n序列号:%3s,\n申请人:%4s,\n申请时间:%5s";
        public static final String OLDDEVICE_STATE_AUDIT = "%1s，你好!\n有一个%2s申请需要审核。\n机型:%3s,\n序列号:%4s,\n申请人:%5s,\n申请时间:%6s";
        public static final String HOUSE_STATE_AUDIT = "%1s，你好!\n有一个%2s申请需要审核。\n房屋名称:%3s,\n房屋位置:%4s,\n申请人:%5s,\n申请时间:%6s";
        public static final String Device_Message = "%1s，你好!\n有一个新机交付已经%2s。\n交车地址:%3s,\n机型:%4s,\n序列号:%5s";
        /**
         * 需要审核
         */
        public static final String Device_AUDIT_AUDIT_MESSAGE = "【审核】%1s提交了\"新机入库申请\"，请审核！";
        public static final String Device_AUDIT_STATE_MESSAGE = "【审核】%1s提交了\"新机交付申请\"，请审核！";
        public static final String OLDDEVICE_AUDIT_STATE_MESSAGE = "【审核】%1s提交了\"%1s申请\"，请审核！";

        /**
         * 审核通过
         */
        public static final String DEVICE_AUDIT_PASS = "%1s，你好!\n你提交的%2s已通过!\n机型:%3s,\n序列号:%4s,\n审核人:%5s,\n审核时间:%6s";
        public static final String HOUSE_AUDIT_PASS = "%1s，你好!\n你提交的%2s已通过!\n房屋名称:%3s,\n房屋位置:%4s,\n审核人:%5s,\n审核时间:%6s";
        /**
         * 申请驳回
         */
        public static final String DEVICE_APPLICATION_REJECT = "%1s，你好!\n你提交的%2s，已被驳回!\n机型:%3s,\n序列号:%4s,\n原因:%5s,\n审核人:%6s,\n审核时间:%7s";
        public static final String HOUSE_APPLICATION_REJECT = "%1s，你好!\n你提交的%2s，已被驳回!\n房屋名称:%3s,\n房屋位置:%4s,\n原因:%5s,\n审核人:%6s,\n审核时间:%7s";
        /**
         * 申请驳回
         */
        public static final String DEVICE_APPLICATION_REJECT_MESSAGE = "【通知】您申请的\"%1s\"已被%2s驳回";
        /**
         * 申请通过
         */
        public static final String DEVICE_APPLICATION_PASS_MESSAGE = "【通知】您提交的\"%1s\"%2s已通过!";
        //-------合同---------START---------
        /**
         * 需要审核
         */
        public static final String CONTRACT_AUDIT_AUDIT = "%1s，你好!\n有一个合同申请需要审核。\n机型：%2s\n价格：¥%3s 元\n申请人：%4s\n申请时间：%5s";
        /**
         * 审核通过
         */
        public static final String CONTRACT_AUDIT_PASS = "%1s，你好!\n你审核的合同申请已通过!\n机型：%2s\n价格：¥%3s 元\n申请人：%4s\n审核时间：%5s";
        /**
         * 申请驳回
         */
        public static final String CONTRACT_APPLICATION_REJECT = "%1s，你好!\n你提交的合同申请，已被驳回!\n机型：%2s\n价格：¥%3s 元\n原因：%4s \n审核人：%5s\n审核时间：%6s";
        /**
         * 申请通过
         */
        public static final String CONTRACT_APPLICATION_PASS = "%1s，你好!\n你提交的合同申请已通过!\n机型：%2s\n价格：¥%3s 元\n审核人：%4s\n审核时间：%5s";
        /**
         * 需要审核
         */
        public static final String CONTRACT_AUDIT_AUDIT_MESSAGE = "【审核】%1s提交了\"合同申请\"，请审核！";
        /**
         * 申请驳回
         */
        public static final String CONTRACT_APPLICATION_REJECT_MESSAGE = "【通知】你申请的\"合同申请\"已被%1s驳回";
        /**
         * 申请通过
         */
        public static final String CONTRACT_APPLICATION_PASS_MESSAGE = "【通知】你提交的\"合同申请\"%1s已通过!";
        /**
         * 考勤推送
         */
        public static final String SIGN_PUSH_MESSAGE = "【今日考勤】%1s已签到。";
        public static final String SIGN_REMIND_MESSAGE = "【今日考勤】迟到/缺勤提醒。";
        public static final String SIGN_REMIND_MESSAGE_WE = "【今日考勤】迟到/缺勤提醒。<a href='%1s'>点此查看</a>";
        public static final String SIGN_PUSH_MESSAGE_WE = "【今日考勤】%1s已签到。<a href='%2s'>点此查看</a>";


        /**
         * 考勤签退推送下面面访
         */
        public static final String SIGN_OUT_PUSH_MESSAGE = "【今日考勤】%1s已签退。";
        public static final String SIGN_OUT_PUSH_MESSAGE_WE = "【今日考勤】%1s已签退。<a href='%2s'>点此查看</a>";
        /**
         * 今日计划
         */
        public static final String TODAY_PLAN_MESSAGE = "【今日计划】数据已生成。";
        public static final String TODAY_PLAN_MESSAGE_WE = "【今日计划】数据已生成。<a href='%1s'>点此查看</a>";
        /**
         * 首次面访
         */
        public static  final String FIRST_VISIT_MESSAGE="【首次面访】数据已生成。";
        public static  final String FIRST_VISIT_MESSAGE_WE="【首次面访】数据已生成。<a href='%1s'>点此查看</a>";
        public static  final String FIRST_VISIT_MESSAGE_ERROR="【首次面访】%1s时间/距离不合理提醒。";
        public static  final String FIRST_VISIT_MESSAGE_ERROR_WE="【首次面访】%1s时间/距离不合理提醒。<a href='%2s'>点此查看</a>";


        /**
         * 微信转发
         */
        public static  final String WECHAT_FORWARD_MESSAGE_ERROR="【微信转发】未按规定数量转发提醒。";
        public static  final String WECHAT_FORWARD_MESSAGE_ERROR_WE="【微信转发】未按规定数量转发提醒。<a href='%1s'>点此查看</a>";
        /**
         * 上午面访
         */
        public static final String AM_VISIT_MESSAGE = "【上午面访】数据已生成。";
        public static final String AM_VISIT_MESSAGE_WE = "【上午面访】数据已生成。<a href='%1s'>点此查看</a>";
        /**
         * 应收快到期
         */
        public static final String YS_KDQ_MESSAGE = "【应收快到期】客户%1s快到期。";
        public static final String YS_KDQ_MESSAGE_WE = "【应收快到期】客户:%1s。<a href='%2s'>点此查看</a>";

        /**
         * 应收快到期
         */
        public static final String YS_YQ_MESSAGE = "【应收逾期】客户%1s已逾期。";
        public static final String YS_YQ_MESSAGE_WE = "【应收逾期】客户:%1s。<a href='%2s'>点此查看</a>";

        /**
         * 免息申请驳回
         */
        public static final String FREE_OUT_REPAYMENT = "%1s，你好!\n你提交的免息申请，已被驳回!\n原因：%2s \n审核人：%3s\n审核时间：%4s";
        public static final String FREE_APPLICATION_REJECT_MESSAGE = "【通知】你申请的\"免息申请\"已被%1s驳回";
        /**
         * 免息申请通过
         */
        public static final String FREE_PASS_REPAYMENT = "%1s，你好!\n你提交的免息申请，申请已通过!";
        public static final String FREE_APPLICATION_PASS_MESSAGE = "【通知】你提交的\"免息申请\"%1s已通过!";
        /**
         * 免息申请审核中
         */
        public static final String FREE_AUDIT_REPAYMENT = "%1s，你好!\n有一个免息申请需要审核<a href='%2s'>点此审核</a>。\n客户：%3s\n申请人：%4s\n申请时间：%5s";
        public static final String FREE_AUDIT_REPAYMENT_PC = "%1s，你好!\n有一个免息申请需要审核。客户：%2s 申请人：%3s 申请时间：%4s";
        public static final String FREE_AUDIT_AUDIT_MESSAGE = "【审核】%1s提交了\"免息申请\"，请审核！";
        //-------合同--------- END-------

        /*//-------用款跟踪---------START---------
        public static final String REFUND_AUDIT_MESSAGE = "【审核】%1s提交了\"用款保证金跟踪\"，请审核！";
        public static final String REFUND_AUDIT = "%1s，你好!\n%2s提交了用款保证金跟踪，请审核!\n申请人:%3s,\n申请时间:%4s";
        public static final String REFUND_AUDIT_PASS_MESSAGE = "【通知】你提交的\"用款保证金跟踪\"，%1s已通过！";
        public static final String REFUND_AUDIT_PASS = "%1s，你好!\n你提交的\"用款保证金跟踪\"，已通过!\n审核人:%2s,\n审核时间:%3s";
        public static final String REFUND_AUDIT_REJECT_MESSAGE = "【通知】你提交的\"用款保证金跟踪\"，%1s已驳回！";
        public static final String REFUND_AUDIT_REJECT = "%1s，你好!\n你提交的\"用款保证金跟踪\"，已驳回!\n审核人:%2s,\n审核时间:%3s";
        public static final String REFUND_PAY_PASS_MESSAGE = "【通知】%1s提交的\"用款保证金跟踪\"已付款，需要编辑！";
        public static final String REFUND_PAY_PASS = "%1s，你好!\n%2s提交的\"用款保证金跟踪\"，已经付款，需要编辑!\n付款人:%3s,\n付款时间:%4s";
        public static final String REFUND_AUDIT_PASS2 = "%1s，你好!\n你提交的\"用款保证金跟踪\"，已通过,需要编辑!\n审核人:%2s,\n审核时间:%3s";
        public static final String REFUND_AUDIT_PASS_MESSAGE2 = "【通知】你提交的\"用款保证金跟踪\"，%1s已通过，需要编辑！";*/
        //-------用款跟踪--------- END-------
        //-------应收台账(区域经理、大区经理、区域支持、接管区域经理)离职发消息给数据专员--------- -START-------
        public static final String RESIGNATION_YSTZ = "你提交的\"应收台账\"%1s-%2s，已经离职，需要重新编辑！";
        public static final String RESIGNATION_YSTZ_MESSAGE = "【通知】\"应收台账\"%1s-%2s已经离职，需编辑！";
        public static final String RESIGNATION_YSTZ_MESSAGE2 = "【通知】%1s-%2s已经离职,需要修改相关应收台账人员信息！";

        //-------应收台账(区域经理、大区经理、区域支持、接管区域经理)离职发消息给数据专员--------- -START-------

        /**
         * 工作报告未阅读
         */
        public static final String REPORT_MESSAGE_ERROR = "【报告阅读】工作报告未读/未发送提醒。";
        public static final String REPORT_MESSAGE_ERROR_WE = "【报告阅读】工作报告未读/未发送提醒。<a href='%1s'>点此查看</a>";
    }
    /**
     * 普通secret
     */
//    public static final String CROP_SECRET = "mPvIrMWPEEiKU9pLFdo8J27dkz8rabNGHZch-n5Dth4";
    /**
     * 通讯录secret
     */
    public static final String CONTACTS_SECRET = "PyIxQWzYtizt7ozlBL0nfM6zELT_Orv1L4xBNWZd_Oc";


    public TokenDao() {
        super.iBaseEntity = new TokenEntity();
    }

    public List<JSONObject> getTokenByType(int type) {

        StringBuffer condition = new StringBuffer();
        condition.append("AND TYPE=" + type + "AND COMPANY_ID='" + WeChatConst.GGXQ_Company_Id + "' ORDER BY CREATE_TIME DESC ");
        List<JSONObject> list = this.getJSONListByCondition(condition.toString(), null);
        return list;
    }

    public List<TokenEntity> getEntityListByCondition(String condition, Object[] params) {
        List<JSONObject> jsonList = getJSONListByCondition(condition, params);
        List<TokenEntity> entityList = new ArrayList<>();
        for (int i = 0; i < jsonList.size(); i++) {
            TokenEntity entity = (TokenEntity) convertJson2Entity(jsonList.get(i));
            entityList.add(entity);
        }
        return entityList;
    }

    @Override
    public IBaseEntity convertJson2Entity(JSONObject json) {
        return JSON.toJavaObject(json, TokenEntity.class);
    }

    public String save(String jsonData, int type) {
        removeByCondition("AND COMPANY_ID='" + WeChatConst.GGXQ_Company_Id + "' AND TYPE=" + type, new String[]{});
        TokenEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), TokenEntity.class);
        add(entity);
        return entity.getId();
    }

    public JSONObject getToken() {
        StringBuffer condition = new StringBuffer();
        condition.append("AND TYPE=2 AND COMPANY_ID='" + WeChatConst.GGXQ_Company_Id + "' ORDER BY CREATE_TIME DESC ");
        List<JSONObject> list = getJSONListByCondition(condition.toString(), new Object[]{});
        return newToken(list, cropSecret);
    }

    /**
     * 获取access_token
     */
    public JSONObject getAccessToken(String secret) {
        TokenEntity accessToken = null;

        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww088b587bfe5ec85c&corpsecret=" + secret;
        JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new TokenEntity();
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
                accessToken.setCompanyId("" + WeChatConst.GGXQ_Company_Id + "");
                //保存到数据库
                if (cropSecret.equals(secret)) {
                    accessToken.setType(WeChatConst.weChat_enterprise_type);
                    save(JSON.toJSONString(accessToken), WeChatConst.weChat_enterprise_type);
                }
                if (CONTACTS_SECRET.equals(secret)) {
                    accessToken.setType(WeChatConst.weChat_enterprise_contacts_type);
                    save(JSON.toJSONString(accessToken), WeChatConst.weChat_enterprise_contacts_type);
                }
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                //log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return (JSONObject) JSON.toJSON(accessToken);
    }

    public JSONObject getContactsToken() {
        StringBuffer condition = new StringBuffer();
        condition.append("AND TYPE=3 AND COMPANY_ID='" + WeChatConst.GGXQ_Company_Id + "' ORDER BY CREATE_TIME DESC ");
        List<JSONObject> list = getJSONListByCondition(condition.toString(), null);
        return newToken(list, CONTACTS_SECRET);
    }

    private JSONObject newToken(List<JSONObject> list, String contactsSecret) {
        if (list != null && list.size() > 0) {
            //判断是否超2小时
            TokenEntity entity = (TokenEntity) convertJson2Entity(list.get(0));
            if (Math.floor((getCurrentTime().getTime() - entity.getCreateTime().getTime()) / 1000) > 7200) {
                return getAccessToken(contactsSecret);
            } else {
                return list.get(0);
            }
        } else {
            //token不存在
            return getAccessToken(contactsSecret);
        }
    }

    public JSONObject sendTextMsg(String jsonData) {
        JSONObject obj = JSON.parseObject(jsonData);
        String userIds = obj.getString("userIds");
        String content = obj.getString("content");
        String invaliduser = "";
        if (userIds.contains("|")) {
            List<String> userId = BaseJdbcDao.stringToLists(userIds);
            for (String id : userId) {
                obj = chooseUserCompany(id, content);
                if (!obj.getString("errcode").equals("0")) {
                    return obj;
                }
            }
        } else {
            obj = chooseUserCompany(userIds, content);
        }
        return obj;
    }

    public JSONObject SignRemind(StringBuilder sb) {
        String content = String.format(SIGN_REMIND, DateUtils.parse(new Date(), "yyyy-MM-dd HH:mm"));
        JSONObject JSYFJsonObject = new JSONObject();
        JSYFJsonObject.put("agentid", companyMessageDao.getCompanyMessageByCompanyId(WeChatConst.JSYF_Company_Id).getString("APPLICATION_ONE_AGENTID"));
        JSYFJsonObject.put("touser", sb);
        JSONObject text = new JSONObject();
        text.put("content", content);
        JSYFJsonObject.put("text", text);
        JSYFJsonObject.put("msgtype", "text");
        HttpUtil.request(WeChatConst.send_message_url.replace("ACCESS_TOKEN", companyTokenFacade.getApplicationToken(WeChatConst.JSYF_Company_Id, WeChatConst.weChat_enterprise_type)), "POST", JSYFJsonObject.toJSONString());
        JSONObject GGXQJsonObject = new JSONObject();
        GGXQJsonObject.put("agentid", companyMessageDao.getCompanyMessageByCompanyId(WeChatConst.GGXQ_Company_Id).getString("APPLICATION_ONE_AGENTID"));
        GGXQJsonObject.put("touser", sb);
        GGXQJsonObject.put("text", text);
        GGXQJsonObject.put("msgtype", "text");
        HttpUtil.request("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + getToken().getString("accessToken"), "POST", GGXQJsonObject.toJSONString());
        return null;
    }


    public JSONObject chooseUserCompany(String userId, String content) {
        String companyId = getCompanyIdByUserID(userId);
        String requestUrl = null;
        JSONObject paramJsonObject = new JSONObject();
        switch (companyId) {
            case WeChatConst.JSYF_Company_Id: {
                paramJsonObject.put("agentid", companyMessageDao.getCompanyMessageByCompanyId(WeChatConst.JSYF_Company_Id).getString("APPLICATION_ONE_AGENTID"));
                String accessToken = companyTokenFacade.getApplicationToken(WeChatConst.JSYF_Company_Id, WeChatConst.weChat_enterprise_type);
                requestUrl = WeChatConst.send_message_url.replace("ACCESS_TOKEN", accessToken);
            }
            break;
            case WeChatConst.SSWY_Company_Id: {
                paramJsonObject.put("agentid", companyMessageDao.getCompanyMessageByCompanyId(WeChatConst.SSWY_Company_Id).getString("APPLICATION_ONE_AGENTID"));
                String accessToken = companyTokenFacade.getApplicationToken(WeChatConst.SSWY_Company_Id, WeChatConst.weChat_enterprise_type);
                requestUrl = WeChatConst.send_message_url.replace("ACCESS_TOKEN", accessToken);
            }
            break;
            case WeChatConst.NMGLA_Company_Id: {
                paramJsonObject.put("agentid", companyMessageDao.getCompanyMessageByCompanyId(WeChatConst.NMGLA_Company_Id).getString("APPLICATION_ONE_AGENTID"));
                String accessToken = companyTokenFacade.getApplicationToken(WeChatConst.NMGLA_Company_Id, WeChatConst.weChat_enterprise_type);
                requestUrl = WeChatConst.send_message_url.replace("ACCESS_TOKEN", accessToken);
            }
            break;
            default: {
                JSONObject tokenObject = getToken();
                String token = tokenObject.getString("accessToken");
                requestUrl = " https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
                //String content = "这是一条测试文字消息,哈哈哈~\n还能加链接<a href=\"http://baidu.com\">百度</a>";
                paramJsonObject.put("agentid", agentId);
            }
        }
        paramJsonObject.put("touser", userId);
        JSONObject contentObj = new JSONObject();
        contentObj.put("content", content);
        paramJsonObject.put("text", contentObj);
        paramJsonObject.put("msgtype", "text");
        // 调用接口
        JSONObject jsonObject = HttpUtil.request(requestUrl, "POST", paramJsonObject.toJSONString());
        // 如果请求成功
        if (null != jsonObject) {
            return jsonObject;
        }
        return null;
    }

    public JSONObject getAllStaff() {
        JSONObject tokenObject = getToken();
        String token = tokenObject.getString("accessToken");
        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token=" + token + "&agentid=" + agentId;
        JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            if ("0".equals(jsonObject.getString("errcode"))) {
                return jsonObject.getJSONObject("allow_userinfos");
            } else {
                //失败
                return null;
            }
        } else {
            return null;
        }
    }

    public JSONObject updateStaff(String jsonString) {
        JSONObject obj = JSON.parseObject(jsonString);
        String userId = obj.getString("userId");
        String name = obj.getString("name");
        String tel = obj.getString("tel");

        JSONObject tokenObject = getContactsToken();
        String token = tokenObject.getString("accessToken");
        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + token;
        JSONObject paramJsonObject = new JSONObject();
        paramJsonObject.put("userid", userId);
        paramJsonObject.put("name", name);
        paramJsonObject.put("mobile", tel);
        String[] departArr = {"1"};
        paramJsonObject.put("department", departArr);//默认第一个
        JSONObject jsonObject = HttpUtil.request(requestUrl, "POST", paramJsonObject.toJSONString());
        // 如果请求成功
        if (null != jsonObject) {
            return jsonObject;
        }
        return null;
    }

    public JSONObject entry(String jsonString) {
        JSONObject obj = JSON.parseObject(jsonString);
        String userId = obj.getString("userId");
        String name = obj.getString("name");
        String tel = obj.getString("tel");

        JSONObject tokenObject = getContactsToken();
        String token = tokenObject.getString("accessToken");
        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + token;
        JSONObject paramJsonObject = new JSONObject();
        paramJsonObject.put("userid", userId);
        paramJsonObject.put("name", name);
        paramJsonObject.put("mobile", tel);
        String[] departArr = {"1"};
        paramJsonObject.put("department", departArr);//默认第一个
        JSONObject jsonObject = HttpUtil.request(requestUrl, "POST", paramJsonObject.toJSONString());
        // 如果请求成功
        if (null != jsonObject) {
            return jsonObject;
        }
        return null;
    }

    public JSONObject leave(String userId) {
        try {
            JSONObject tokenObject = getContactsToken();
            String token = tokenObject.getString("accessToken");
            String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + token + "&userid=" + userId;
            JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);
            // 如果请求成功
            if (null != jsonObject) {
                return jsonObject;
            }
        } catch (Exception e) {

        }
        return null;
    }

    public static final String MASTER_SECRET = "6c350b1e12a011a51c10f577";
    public static final String APP_KEY = "a30e41976de55ec0ff5ca507";
    public static JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());

    public static PushPayload buildPushObject_android_tag_alertWithTitle(String toUser, String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(toUser))
                .setNotification(Notification.android(content, "滚滚向前", null))
                .build();
    }

    /**
     * 发送推送通知
     */
    public void sendJPushMsg(String toUser, String content) {


        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_android_tag_alertWithTitle(toUser, content);

        try {
            PushResult result = jpushClient.sendPush(payload);
            //LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            //LOG.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
           /* LOG.error("Should review the error, and fix the request", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());*/
        }
    }

    /**
     * 获取指定推送tag
     *
     * @param registration_id
     * @return
     */
    public String getJPushTag(String registration_id) {
        String tag = "";
        try {
            TagAliasResult result = jpushClient.getDeviceTagAlias(registration_id);
            tag = result.tags.toString();
          /*  LOG.info(result.alias);
            LOG.info(result.tags.toString());*/
        } catch (APIConnectionException e) {
            // LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
           /* LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());*/
        }
        return tag;
    }

    public String getCompanyIdByUserID(String userId) {
        //LOG.info(userId);
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT \n");
        sb.append("companyId \n");
        sb.append("FROM \n");
        sb.append("v_sys_user \n");
        sb.append("where 1=1 \n");
        sb.append("and delFlag=0 \n");
        sb.append("and jobState!=1 \n");
        sb.append("and main=1 \n");
        sb.append("and id=?\n");
        super.appendPageSql(sb, 1, Integer.MAX_VALUE);
        List<JSONObject> jsonList = super.queryForJsonList(sb.toString(), new Object[]{userId});
        if (jsonList != null && jsonList.size() > 0) {
            return jsonList.get(0).getString("companyId");
        } else {
            return "";
        }
    }

}

